package com.zhh.front.service;

import com.alibaba.fastjson.JSONObject;
import com.zhh.api.service.UserService;
import com.zhh.common.util.HttpClientUtils;
import com.zhh.front.config.AlyRealnameConfig;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class RealnameServiceImpl {

    @Resource
    private AlyRealnameConfig realnameConfig;

    @DubboReference(interfaceClass = UserService.class,version = "1.0")
    private UserService userService;

    //实名认证
    public int handleRealname(String phone, String name, String idCard){
        int send = 0;

        //请求头
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + realnameConfig.getAppkey());
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

        //请求体
        Map<String, Object> bodys = new HashMap<String, Object>();
        bodys.put("id_number", idCard);
        bodys.put("name", name);

        try {
            //使用HttpClient发送post请求给第三方
            String result = HttpClientUtils.doPost(realnameConfig.getUrl(), headers, bodys);
            //解析响应结果
            if(StringUtils.isNotBlank(result)){
                JSONObject jsonObject = JSONObject.parseObject(result);
                //判断第三方接口是否调用成功
                if("OK".equals(jsonObject.getString("status"))){
                    //判断实名认证是否成功
                    if("1".equals(jsonObject.getString("state"))){
                        //更新数据库实名认证信息
                        boolean modifyResult = userService.modifyRealname(phone,name,idCard);
                        if(modifyResult){
                            send = 1; //实名验证成功
                        }else{
                            send = 3; //实名认证成功，更新数据库失败
                        }
                    }else{
                        send = 2; //实名验证失败，名字和身份证不匹配
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return send;
    }

}
